// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

import axios from 'axios'  // 一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端

import qs from 'qs'

Vue.prototype.$axios=axios
Vue.prototype.qs = qs
axios.defaults.baseURL = "http://localhost:8081/"     //配置默认发送请求到http://127.0.0.1:8081/

Vue.config.productionTip = false

// http request 拦截器
axios.interceptors.request.use(
  function (config) {
    if (!window.sessionStorage.getItem('token')) {
      // console.log('>>>>> ' + router.currentRoute.fullPath)
      router.replace({
        path: '/login',
        query: {redirect: router.currentRoute.fullPath}
      })
    } else {
      console.log(window.sessionStorage.getItem('token'))
      config.headers.Authorization = window.sessionStorage.getItem('token')
    }
    console.log(config)
    return config;
  }, function (error) {
    return Promise.reject(error);
  })

axios.interceptors.response.use(
  function (response) {
    return response
  },
  function (error) {
    if (error.response) {
      if (error.response.status == 401) {
        sessionStorage.removeItem('token')
        router.replace({
          href: '/login',
          query: {redirect: router.currentRoute.fullPath}
        })
      } else {
        next()
      }
      return Promise.reject(error.response.data)  // 返回接口返回的错误信息
    }
  })

// url 拦截
router.beforeEach((to, from, next) => {
  if (to.path == '/login') {
    sessionStorage.removeItem('token');
  }
  let user = sessionStorage.getItem('user');
  if (!user && to.path != '/login') {
    next({ path: '/login' })
  } else if(user && to.path != '/login' && to.path != '/404' && to.path != '/'){
    // let permis = user.rolePermis
    // let allow = false
    // for (var i = 0,length = permis.length; i < length; i++) {
    //   let children = permis[i].children
    //   for (var j = 0,leng = children.length; j < leng; j++) {
    //     if(to.path === children[j].url) {
    //       allow = true
    //     }
    //   }
    // }
    let allow = false
    if(to.path === '/hello'){
      allow = true
    }
    if (allow) {
      console.log('有权限进入' + to.path);
      next()
    } else {
      console.log('没有权限进入' + to.path);
      next({ path: '/404' })
    }
  } else {
    next()
  }
})


/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})
